package com.ztgf.order.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.common.utils.DateUtils;
import com.ztgf.order.common.config.YmlConfig;
import com.ztgf.order.mapper.OrderShipMapper;
import com.ztgf.order.models.bo.LogisticsEditBO;
import com.ztgf.order.models.bo.OrderShipSaveBO;
import com.ztgf.order.models.constant.OrderExpireTimeConstant;
import com.ztgf.order.models.dto.OrderExpirationDateDTO;
import com.ztgf.order.models.dto.OrderInfoDTO;
import com.ztgf.order.models.dto.OrderInvoiceDTO;
import com.ztgf.order.models.dto.OrderShipDTO;
import com.ztgf.order.models.enums.OrderStateEnum;
import com.ztgf.order.models.service.*;
import com.ztgf.shopping.models.service.shop.IShopInfoService;
import com.ztgf.shopping.models.vo.shop.ShopInfoVO;
import com.ztgf.sms.models.bo.SmsInfoSaveBO;
import com.ztgf.sms.models.service.ISmsInfoService;
import com.ztgf.sys.models.dto.SysDictDTO;
import com.ztgf.sys.models.service.ISysDictService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.ztgf.common.utils.UtilConstants.isNull;

/**
 * 订单发货表控制器
 *
 * @author chenyu.wang
 * @Date 2020-06-29 11:26:15
 */
@Slf4j
@DubboService
@Lazy
public class OrderShipServiceImpl extends ServiceImpl<OrderShipMapper, OrderShipDTO> implements IOrderShipService {

    @Resource
    private YmlConfig ymlConfig;
    @Autowired
    private IOrderStatusService orderStatusService;
    @Autowired
    private IOrderExpirationDateService orderExpirationDateService;
    @DubboReference
    private ISysDictService sysDictService;
    @Autowired
    private IOrderInvoiceService orderInvoiceService;
    @Autowired
    private IOrderInfoService orderInfoService;
    @DubboReference
    private IShopInfoService shopInfoService;
    @DubboReference
    private ISmsInfoService smsInfoService;
    @Autowired
    private IOrderDeadlineRecordService orderDeadlineRecordService;

    @Override
    public Result<List<String>> addOrderShip(OrderShipSaveBO bo) {
//        Result<List<String>> result = new Result<>();
//        Wrapper<OrderShipDTO> wrapper = new EntityWrapper<>();
//        wrapper.eq("order_id", bo.getOrderId());
//        wrapper.orderBy("create_time", true);
//        List<OrderShipDTO> list = this.selectList(wrapper);
//        if (!isNull(list)) {
//            for (OrderShipDTO dto : list) {
//                //如果是分批发货则可以发多次，否则一个订单只能发一次
//                if (dto.getShipWay() == 0) {
//                    result.setCode(CodeEnum.FAIL_ORDER_SHIP_320000.getCode());
//                    result.setMsg(CodeEnum.FAIL_ORDER_SHIP_320000.getMsg());
//                    return result;
//                } else {
//                    continue;
//                }
//            }
//        }

        //选择物流
        return this.chooseLogistics(bo);
//        if (bo.getType() == 0) {
//            //选择物流
//            return this.chooseLogistics(bo);
//        } else if(bo.getType() == 1){
//            // 自己联系物流
//            return this.oneSelfContactLogistics(bo);
//
//        }
    }

    @Override
    public OrderShipDTO getByOrderId(Long orderId) {
        Wrapper<OrderShipDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id", orderId);
        return this.selectOne(wrapper);
    }

    @Override
    public List<OrderShipDTO> getListByOrderId(Long orderId) {
        Wrapper<OrderShipDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id", orderId);
        wrapper.orderBy("create_time", false);
        return this.selectList(wrapper);
    }

    @Override
    public Result updateLogistics(LogisticsEditBO saveBO) {
        OrderShipDTO dto = new OrderShipDTO();
        dto.setId(saveBO.getId());
        dto.setLogisticsCompany(saveBO.getCompanyName());//物流公司名称
        dto.setCompanyCode(saveBO.getCompanyCode());//物流公司编码
        dto.setShipmentNumber(saveBO.getMailNo());//物流单号
        dto.setType(saveBO.getType());
        dto.setContactInformation(saveBO.getContactInformation());
        if(updateById(dto)){
            return new Result();
        } else {
            return new Result(CodeEnum.FAIL_100011);
        }
    }

    /**
     * @description:发货后修改订单发票信息
     * @author: chenyu.wang
     * @date: 2020-08-17
     * @param:
     * @return:
     */
    private void updateInvoice(String code, String number, String file, Long orderId) {
        //修改发票状态
        orderStatusService.updateOrderInvoiceState(orderId);
        //修改发票信息
        Wrapper<OrderInvoiceDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id", orderId);
        OrderInvoiceDTO invoiceDTO = orderInvoiceService.selectOne(wrapper);
        if (null == invoiceDTO) {
            log.info("*****暂无订单发票信息*****");
        } else {
            OrderInvoiceDTO updateDto = new OrderInvoiceDTO();
            updateDto.setId(invoiceDTO.getId());
            updateDto.setTaxpayerId(code);
            updateDto.setInvoiceUrl(file);
            orderInvoiceService.updateById(updateDto);
        }
    }

    /**
     * @description:发送短信
     * @author: chenyu.wang
     * @date: 2020-09-16
     * @return:
     */
    @Async
    public void sendSMS(Long orderId) {
        //查询订单
        OrderInfoDTO orderInfoDTO = orderInfoService.selectById(orderId);
        if (orderInfoDTO != null) {
            List<Long> idList = new ArrayList<>();
            idList.add(orderInfoDTO.getBuyShopId());//买家店铺id
            idList.add(orderInfoDTO.getSellShopId());//卖家店铺id
            List<ShopInfoVO> users = shopInfoService.getByShopIds(idList);//获取店铺手机号
            if (!isNull(users)) {
                for (ShopInfoVO user : users) {
                    try {
                        SmsInfoSaveBO smsInfoSaveBO = new SmsInfoSaveBO();
                        smsInfoSaveBO.setMobile(user.getMobile());
                        smsInfoService.saveOrderStatus(smsInfoSaveBO);//发送短信
                    } catch (Exception e) {
                        log.info("发货发送短信失败!");
                        e.printStackTrace();
                    }
                }
            } else {
                log.info("暂未查询到店铺手机号,发送短信失败!");
            }
        } else {
            log.info("暂无订单信息,发送短信失败!");
        }

    }

    /**
     * @Description: 发货选择物流
     * @Author: chenyu.wang
     * @Param: [bo]
     * @Date: 2020.10.22 上午 9:37
     */
    private Result chooseLogistics(OrderShipSaveBO bo) {
        Result result = new Result<>();
        OrderShipDTO dto = new OrderShipDTO();
        if(bo.getId() == null){
            dto.setId(ymlConfig.getPkId());
        } else {
            dto.setId(bo.getId());
        }

        dto.setCreateUserId(bo.getCreateUserId());//店铺id
        dto.setOrderId(bo.getOrderId());//订单id
        dto.setLogisticsCompany(bo.getLogisticsCompany());//物流公司名称
        dto.setCompanyCode(bo.getCompanyCode());//物流公司编码
        dto.setShipmentNumber(bo.getShipmentNumber());//物流单号
        dto.setContactInformation(bo.getContactInformation());
        dto.setShipWay(bo.getShipWay());//发货方式
        dto.setDeparture(bo.getDeparture());//出发地
        dto.setDestination(bo.getDestination());//目的地
        //保留收货人手机号后四位
        if (!TextUtils.isEmpty(bo.getLastFourPhoneNumber()) && bo.getLastFourPhoneNumber().length() >= 4) {
            dto.setLastFourPhoneNumber(bo.getLastFourPhoneNumber().substring(0, 4));
        }
        dto.setType(bo.getType());
        boolean flag = this.updateById(dto);
        if (!flag) {
            flag = this.insert(dto);
            if(!flag){
                result.setCode(CodeEnum.FAIL_ORDER_SHIP_320001.getCode());
                result.setMsg(CodeEnum.FAIL_ORDER_SHIP_320001.getMsg());
                return result;
            }
        } else {
            return result;
        }
        //更改订单状态,分批发货不改，全部发货改为已发货状态
        if (bo.getShipWay() == 0) {
            orderStatusService.updateOrderShipWay(bo.getOrderId());
        }
        //更改订单发票状态
        if (StringUtils.isNotBlank(bo.getInvoiceCode()) && StringUtils.isNotBlank(bo.getInvoiceNumber())
                && StringUtils.isNotBlank(bo.getInvoiceFile())) {
            this.updateInvoice(bo.getInvoiceCode(), bo.getInvoiceNumber(), bo.getInvoiceFile(), bo.getOrderId());
        }
        if(bo.getShipWay() == 0){
            Date currentDateTime = DateUtils.getCurrentDateTime();//当前时间
            SysDictDTO sysDictDTO = sysDictService.getByName(OrderExpireTimeConstant.ORDER_WAIT_SIGN);//订单待签收倒计时
            String time = sysDictDTO.getValue();
            Date expireTime = DateUtils.addDay(currentDateTime, Integer.parseInt(time));//过期时间
            OrderExpirationDateDTO orderTime = orderExpirationDateService.getByOrderId(bo.getOrderId());
            if (null != orderTime) {
                OrderExpirationDateDTO updateOrderTime = new OrderExpirationDateDTO();
                updateOrderTime.setId(orderTime.getId());
                updateOrderTime.setExpirationTime(expireTime);//修改过期时间
                updateOrderTime.setStatus(OrderStateEnum.ORDER_STATE_ENUM_WAIT_SIGN.getCode());//改变订单状态
                orderExpirationDateService.updateById(updateOrderTime);//重新更新状态
                // 待签收截止时间记录
                orderDeadlineRecordService.add(bo.getOrderId(), 6, expireTime);
                // 全部发货完成时间
                orderDeadlineRecordService.add(bo.getOrderId(), 11, currentDateTime);
            }
        }else{
            // 更改过期时间
            Date currentDateTime = DateUtils.getCurrentDateTime();//当前时间
            SysDictDTO sysDictDTO = sysDictService.getByName(OrderExpireTimeConstant.ORDER_WAIT_SIGN);//订单待签收倒计时
            String time = sysDictDTO.getValue();
            Date expireTime = DateUtils.addDay(currentDateTime, Integer.parseInt(time));//过期时间
            // 待签收截止时间记录
            orderDeadlineRecordService.add(bo.getOrderId(), 5, expireTime);
            // 部分发货时间
            orderDeadlineRecordService.add(bo.getOrderId(), 10, currentDateTime);
        }
        //发送短信
        this.sendSMS(bo.getOrderId());
        result.setCode(CodeEnum.SUCCESS.getCode());
        result.setMsg(CodeEnum.SUCCESS.getMsg());
        return result;
    }

    /**
     * @Description: 发货自己联系物流
     * @Author: chenyu.wang
     * @Param: [bo]
     * @Date: 2020.10.22 上午 9:37
     */
    private Result<List<String>> oneSelfContactLogistics(OrderShipSaveBO bo) {
        Result<List<String>> result = new Result<>();
        OrderShipDTO dto = new OrderShipDTO();
        dto.setId(ymlConfig.getPkId());
        dto.setCreateUserId(bo.getCreateUserId());//店铺id
        dto.setOrderId(bo.getOrderId());//订单id
        dto.setLogisticsCompany(bo.getLogisticsCompany());//物流公司名称/送货员姓名
        if (StringUtils.isNotBlank(bo.getShipmentNumber())) {
            dto.setShipmentNumber(bo.getShipmentNumber());//物流单号
        }
        dto.setContactInformation(bo.getContactInformation());//联系方式
        dto.setShipWay(bo.getShipWay());//发货方式
        dto.setDeparture(bo.getDeparture());//出发地
        dto.setDestination(bo.getDestination());//目的地
        //保留收货人手机号后四位
        if (!TextUtils.isEmpty(bo.getLastFourPhoneNumber()) && bo.getLastFourPhoneNumber().length() >= 4) {
            dto.setLastFourPhoneNumber(bo.getLastFourPhoneNumber().substring(0, 4));
        }
        dto.setType(bo.getType());
        boolean flag = this.insert(dto);
        if (!flag) {
            result.setCode(CodeEnum.FAIL_ORDER_SHIP_320001.getCode());
            result.setMsg(CodeEnum.FAIL_ORDER_SHIP_320001.getMsg());
            return result;
        }
        //更改订单状态,分批发货不改，全部发货改为已发货状态
        if (bo.getShipWay() == 0) {
            orderStatusService.updateOrderShipWay(bo.getOrderId());
        }
        //更改订单发票状态
        if (StringUtils.isNotBlank(bo.getInvoiceCode()) && StringUtils.isNotBlank(bo.getInvoiceNumber())
                && StringUtils.isNotBlank(bo.getInvoiceFile())) {
            this.updateInvoice(bo.getInvoiceCode(), bo.getInvoiceNumber(), bo.getInvoiceFile(), bo.getOrderId());
        }
        //发送短信
        this.sendSMS(bo.getOrderId());
        if (bo.getShipWay() == 0) {
            // 更改过期时间
            Date currentDateTime = DateUtils.getCurrentDateTime();//当前时间
            SysDictDTO sysDictDTO = sysDictService.getByName(OrderExpireTimeConstant.ORDER_WAIT_SIGN);//订单待签收倒计时
            String time = sysDictDTO.getValue();
            Date expireTime = DateUtils.addDay(currentDateTime, Integer.parseInt(time));//过期时间
            OrderExpirationDateDTO orderTime = orderExpirationDateService.getByOrderId(bo.getOrderId());
            if (null != orderTime) {
                OrderExpirationDateDTO updateOrderTime = new OrderExpirationDateDTO();
                updateOrderTime.setId(orderTime.getId());
                updateOrderTime.setExpirationTime(expireTime);//修改过期时间
                updateOrderTime.setStatus(OrderStateEnum.ORDER_STATE_ENUM_WAIT_SIGN.getCode());//改变订单状态
                orderExpirationDateService.updateById(updateOrderTime);//重新更新状态
                // 待签收截止时间记录
                orderDeadlineRecordService.add(bo.getOrderId(), 6, expireTime);
                // 全部发货完成时间
                orderDeadlineRecordService.add(bo.getOrderId(), 11, currentDateTime);
            }
        }else{
            // 更改过期时间
            Date currentDateTime = DateUtils.getCurrentDateTime();//当前时间
            SysDictDTO sysDictDTO = sysDictService.getByName(OrderExpireTimeConstant.ORDER_WAIT_SIGN);//订单待签收倒计时
            String time = sysDictDTO.getValue();
            Date expireTime = DateUtils.addDay(currentDateTime, Integer.parseInt(time));//过期时间
            // 待签收截止时间记录
            orderDeadlineRecordService.add(bo.getOrderId(), 5, expireTime);
            // 部分发货时间
            orderDeadlineRecordService.add(bo.getOrderId(), 10, currentDateTime);


        }
        result.setCode(CodeEnum.SUCCESS.getCode());
        result.setMsg(CodeEnum.SUCCESS.getMsg());
        return result;
    }



}
